﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FONCREAGROINTEGRAL.Models;

namespace FONCREAGROINTEGRAL.Controllers
{
    public class ctservController : Controller
    {
        public SistIntFoncreagroEntities entidades = new SistIntFoncreagroEntities();
        //
        // GET: /ctserv/
        //id ejercicio mes
        //id1 tipo trabajador
        public ActionResult Index(int id,int id1)
        {
            int start = Convert.ToInt32(Request.QueryString["start"]);
            int limit = Convert.ToInt32(Request.QueryString["limit"]);

            //string area = Convert.ToString(Request.QueryString["query"]);

            var query = entidades.RHCTSGeneral(id, id1).ToList();//.Where(a => (a.Personal).ToUpper().Contains(personal.ToUpper()))/*.Skip(start).Take(limit)*/.ToList();
            return Json(new { grid = query, total = query.Count() }, JsonRequestBehavior.AllowGet);       

        }
        // GET: /ctserv/
        //id ejercicio mes
        //id1 tipo trabajador
        public ActionResult IndexProyecto(int id, int id1)
        {
            int start = Convert.ToInt32(Request.QueryString["start"]);
            int limit = Convert.ToInt32(Request.QueryString["limit"]);

            var query = entidades.RHCTSAreaBanco(id, id1).ToList();
            return Json(new { grid = query, total = query.Count() }, JsonRequestBehavior.AllowGet);
        }
        
        public string CCcts(int id)
        {
            try
            {
                var query = entidades.CCOSTOVACACIONCTSERVs.Where(cccts => cccts.IdCTServ == id)
                    .Join(entidades.CCOSTOes, cccts => cccts.IdCCosto, cc => cc.IdCCosto, (cccts, cc) => new {cc.Codigo });
                var result = query.ToList();
                string cadena = "";
                for (var reg = 0; reg < result.Count(); reg++)
                {
                    cadena = cadena + " " + result.ElementAt(reg).Codigo;
                }

                return cadena;
            }
            catch {
                return "";
            }
        }
        //
        //


        public ActionResult ValidarPagoCTS(int id)
        {
            String strResponse = String.Empty;
            try
            {
                var query = entidades.RHValidarPagoCTS(id).ToList();
                string res = query[0].Resultado.ToString();

                if (res == "1") { strResponse = "CORTA"; }
                else { strResponse = "SIGUE"; }
                return Content(strResponse);
            }
            catch
            {
                return Content("ERROR");
            }
        }

        public ActionResult CalcularCTS(int id)
        {
            String strResponse = String.Empty;
            try
            {
                entidades.RLLENARCTSERV(id);
                strResponse = "OK";
                return Content(strResponse);
            }
            catch
            {
                return Content("ERROR");
            }
        }


        [HttpPost]
        public ActionResult Pagar(int id,int id1)
        {
            String strResponse = String.Empty;
            try
            {
                int IdPersonal = Convert.ToInt32(Session["IdPersonal"].ToString());
                int IdPersonaltmp = IdPersonal;
                DateTime Fecha = Convert.ToDateTime(Request.Form["Fecha"]);
                entidades.GenerarTRANSACCIONPagoCts(IdPersonaltmp, Fecha);
                strResponse = "{success: true,msg:'<b>Se Pago CTS Empleados y Obreros</b>'}";
                return Content(strResponse);
            }
            catch (Exception e)
            {
                string sms = e.Message;
                strResponse = "{success: false,msg:\"" + sms + "(" + "," + id+ ")\"}";
                return Content(strResponse);
            }
        }


        //
        //
        public ActionResult AnularPago(int id)
        {
            try
            {
                entidades.RHAnularPagoCTS(id);
                return Content("1");
            }
            catch
            {
                return Content("0");
            }
        }
        //
        // GET: /ctserv/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        //
        public ActionResult Actualizar(int id)
        {
            var ectserv = entidades.CTSERVs.Single(c => c.IdCTServ == id);
            if (ModelState.IsValid)
            {
                //var ccontrato = new CONTRATOADENDAPERSONAL();
                TryUpdateModel(ectserv);
                ectserv.PorcGratificacion = ectserv.Gratificacion/6;
                ectserv.CTS = ((ectserv.Remuneracion + ectserv.Gratificacion / 6)/12)*6;
                entidades.SaveChanges();
                return Content("OK");
            }
            return Content("Error");

        }
        //
        // GET: /ctserv/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /ctserv/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        
        //
        // GET: /ctserv/Edit/5
 
        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /ctserv/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /ctserv/Delete/5
 
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /ctserv/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }



        public ActionResult Provision(int id, int id1)
        {
            var query = entidades.RHListaProvisionCTS(id, id1).ToList();
            return Json(new { grid = query, total = query.Count() }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult ProvisionD(int id)
        {
            var query = entidades.RHListaCTSXPersona(id).ToList();
            return Json(new { grid = query, total = query.Count() }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult EditCTSProv(int id)
        {
            ViewData["id"] = id;
            return View();
        }

        [HttpPost]
        public ActionResult EditCTSProv(int id, FormCollection collection)
        {
            var ectscontable = entidades.CTSCONTABLEs.Single(ctsc => ctsc.IdCTSContable == id);
            int idccostonew = Convert.ToInt32(Request.Form["IdCCosto"].ToString());
            int idproyecnew = Convert.ToInt32(Request.Form["IdProyecto"].ToString());
            try
            {
                var query = entidades.RHActualizaCCProyCTS(id,idccostonew,idproyecnew).ToList();
                return Content("OK");
            }
            catch
            {
                ViewData["id"] = id;
                return View();
            }
        }

        public ActionResult ListProyectos()
        {
            string area = Convert.ToString(Request.QueryString["query"]);
            var query = entidades.PROYECTOes.Where(p => p.Estado == "EJECUCION");

            if (!String.IsNullOrEmpty(area))
            {
                query = query.Where(a => (a.Nombre).ToUpper().Contains(area.ToUpper()) ||
                    (a.Codigo).ToUpper().Contains(area.ToUpper()));
            }

            var result = (from p in query.OrderBy(p => p.Codigo).ToList()
                          select new
                          {
                             IdProyecto = p.IdProyecto,
                             Codigo = p.Codigo,
                             Proyecto = p.Codigo + " - " + p.AliasProy
                          }).ToList();

            return Json(new { grid = result, total = query.Count() }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult ListCCosto(int id)
        {
            int start = Convert.ToInt32(Request.QueryString["start"]);
            int limit = Convert.ToInt32(Request.QueryString["limit"]);
            string elementogc = Convert.ToString(Request.QueryString["query"]);

            var query = entidades.CONVEPROYs
                .Where(cc => cc.IdProyecto == id)
                .Join(entidades.PROYCOMPs, cpy => cpy.IdConvProy, pyc => pyc.IdConvProy, (cpy, pyc) => new { pyc.IdProyComp })
                .Join(entidades.PROYACTs, pyc => pyc.IdProyComp, pya => pya.IdProycomp, (pyc, pya) => new { pya.IdProyAct })
                .Join(entidades.CCOSTOes, pya => pya.IdProyAct, cc => cc.IdProyAct, (pya, cc) => new { cc.IdCCosto, cc.Codigo, cc.IdElemGasto })
                .Join(entidades.ELEMENTOGASTOes, cc => cc.IdElemGasto, eg => eg.IdElemGasto, (cc, eg) => new { cc.IdCCosto, cc.Codigo, cc.IdElemGasto, eg.NomElemGasto });

            if (!String.IsNullOrEmpty(elementogc))
            {
                query = query.Where(cc => (cc.NomElemGasto).ToUpper().Contains(elementogc.ToUpper()) ||
                    (cc.Codigo).ToUpper().Contains(elementogc.ToUpper()));
            }

            var result = (from cc in query.OrderBy(cc => cc.IdCCosto).Skip(start).Take(limit).ToList()
                          select new
                          {
                              IdCCosto = cc.IdCCosto,
                              CCosto = cc.NomElemGasto,
                              Codigo = cc.Codigo,
                          }).ToList();

            return Json(new { grid = result, total = query.Count() }, JsonRequestBehavior.AllowGet);
        }

    }
}